import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class MallAdViewController {
  final MallAdViewCallbacksHandler _handler;
  final MethodChannel _methodChannel;

  MallAdViewController._(int id, this._handler)
      : _methodChannel = MethodChannel("com.leiusual.mall_ad/view_$id") {
    _methodChannel.setMethodCallHandler(_onMethodCall);
  }

  void fetchAd() {
    _methodChannel.invokeMethod("fetchAd");
  }

  Future _onMethodCall(MethodCall call) async {
    debugPrint("${call.method}");
    switch (call.method) {
      case "onJumpClicked":
        _handler.onJumpClicked();
        break;
      case "onSplashAdDismiss":
        _handler.onSplashAdDismiss();
        break;
      default:
    }
  }
}

class MallAdView extends StatefulWidget {
  final Function(MallAdViewController) callback;
  final MallAdViewCallbacksHandler handler;

  const MallAdView({
    Key key,
    @required this.callback,
    @required this.handler,
  }) : super(key: key);

  @override
  _MallAdViewState createState() => _MallAdViewState();
}

class _MallAdViewState extends State<MallAdView> {
  @override
  Widget build(BuildContext context) {
    if (defaultTargetPlatform == TargetPlatform.android) {
      return AndroidView(
        viewType: "com.leiusual.mall_ad/view",
        onPlatformViewCreated: _onPlatformViewCreated,
      );
    }
    return Container();
  }

  void _onPlatformViewCreated(int id) {
    widget.callback((MallAdViewController._(id, widget.handler)));
  }
}

abstract class MallAdViewCallbacksHandler {
  void onJumpClicked();
  void onSplashAdDismiss();
}
